//
//  HttpClient.m
//  CostFunction
//
//  Created by ss ss on 7/11/12.
//  Copyright (c) 2012 s. All rights reserved.
//

#import "HttpClient.h"

@interface HttpClient()
@property (retain, nonatomic) NSURLConnection* connection;
@property (assign, nonatomic) id delegate_;
@property (retain, nonatomic)  NSMutableString* receiveData;

@end

@implementation HttpClient

@synthesize delegate_;
@synthesize connection;
@synthesize receiveData;

- (id)init
{
    self = [super init];
    self.receiveData = [[NSMutableString alloc]init];
    return self;
}

- (void) dealloc
{
    [self.receiveData release];
    [super dealloc];
}

- (void) requestWithUrl:(NSString*) URL delegate: (id)delegate
{
    assert(URL != nil);
    NSURL *  url = [NSURL URLWithString:URL];
    NSURLRequest* request = [NSURLRequest requestWithURL:url];
    assert(request != nil);
    self.delegate_ = delegate;
    self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
}

- (void)connection:(NSURLConnection *)theConnection didReceiveResponse:(NSURLResponse *)response
// A delegate method called by the NSURLConnection when the request/response 
// exchange is complete.  We look at the response to check that the HTTP 
// status code is 2xx and that the Content-Type is acceptable.  If these checks 
// fail, we give up on the transfer.
{
  
}

- (void)connection:(NSURLConnection *)theConnection didReceiveData:(NSData *)data
// A delegate method called by the NSURLConnection as data arrives.  We just 
// write the data to the file.
{
    NSString* dataString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    if (dataString != nil) {
        [receiveData appendString:dataString];
    }
    
    [dataString release];
}

- (void)connection:(NSURLConnection *)theConnection didFailWithError:(NSError *)error
// A delegate method called by the NSURLConnection if the connection fails. 
// We shut down the connection and display the failure.  Production quality code 
// would either display or log the actual error.
{

}

- (void)connectionDidFinishLoading:(NSURLConnection *)theConnection
// A delegate method called by the NSURLConnection when the connection has been 
// done successfully.  We shut down the connection with a nil status,
{
    [self.delegate_ onNetworkReturn: receiveData];
    assert(theConnection == self.connection);
    if (self.connection != nil) {
        [self.connection cancel];
        self.connection = nil;
    }
    
[receiveData setString:@""];//reset data;

}



@end
